import os
import sys
import time
import docker as d

import sys

sys.path.append("..")

mount_path = '/home/py_process/flask_serverless/core/ready_run_code'
filepath = './core/ready_run_code/temp.py'


def get_instance(m):
    global instance_run
    instance_run = m


def write_code(str, **kw):
    status = 0
    with open(filepath, 'w') as f:
        f.write(str)


def run_code(**kw):
    # out=subprocess.run("python " + filepath,
    #                    shell=True,
    #                    stderr=subprocess.STDOUT,
    #                    stdout=subprocess.PIPE,
    #                    universal_newlines=True)
    #
    # output=out.stdout

    mount_dict = {
        mount_path: {'bind': '/mnt/path', 'mode': 'rw'}
    }
    envi_list = ["PYTHONUNBUFFERED=1"]
    client = d.from_env()
    # todo 现在是运行结束就删除容器
    container = client.containers.run('tensorflow-flask', 'python /mnt/path/temp.py',
                                      detach=True,
                                      volumes=mount_dict,
                                      environment=envi_list,
                                      remove=True,
                                      )

    start_time = time.time()
    with open('./core/log/log.txt', 'w+') as f:
        for i in container.logs(stream=True, stderr=True, timestamps=False):
            j = str(i, encoding="utf-8").replace('\b', '').replace('\r', '\n')
            f.write(j)
            time.sleep(0.1)
            # todo 超时停止
            if time.time() - start_time > 10:
                container.kill()
            instance_run.queue.put({'log': j})
            print(j)
        instance_run.queue.put(0)
    #

    # error = container.logs(stdout=False)
    # if error:
    #     status = -1
    #     error_info = str(error, encoding="utf-8")
    #     # print(error_info)
    # else:
    #     status = 1
    #
    # if status == -1:
    #     return error_info
    # else:
    #     return 1
    return 1


def run(writed_code):
    write_code(writed_code)
    status = run_code()
    return status
